package com.norns.torque

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.norns.torque.bluetooth.ChatServer
import com.norns.torque.entrty.AppDatabase
import com.norns.torque.entrty.WifiDevice
import com.norns.torque.entrty.WifiDeviceDao
import com.norns.torque.listener.ConnectedListener
import com.norns.torque.network.NetworkUtils
import com.norns.torque.socket.ClientSocket
import com.norns.torque.utils.AppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket


class WifiDeviceViewModel : ViewModel() {
    private var deviceDao: WifiDeviceDao? = null
    private var mClientSocket: Socket? = null
    private val _deviceListLiveData = MutableLiveData<List<WifiDevice>>()
    val deviceListLiveData = _deviceListLiveData as LiveData<List<WifiDevice>>

    private val _deviceLiveData = MutableLiveData<WifiDevice>()
    val deviceLiveData = _deviceLiveData as LiveData<WifiDevice>

    private val _connectionState = MutableLiveData<Int>()
    val connectionState = _connectionState as LiveData<Int>


   private val connectedListener:ConnectedListener= object: ConnectedListener {
        override fun onConnected(connectedState: Int) {
            _connectionState.postValue(connectedState)
        }
    }

    companion object {
        const val contentChecked: Int = 792
    }



    fun setDeviceUnConnected() {
        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                val deviceList = _deviceListLiveData.value
                deviceList?.forEach { device ->
                    if (device.address.isNullOrEmpty().not()) {
                        device.contentState = "离线"
                    }
                }
                deviceList?.let {
                    _deviceListLiveData.postValue(deviceList!!)
                }

            }
        }
    }


    fun initDataBase() {
        ClientSocket.addConnectionListener(connectedListener)
        ClientSocket.registerNetwork()
        if (null == deviceDao) {
            viewModelScope.launch {
                withContext(Dispatchers.Default) {
                    val db = AppDatabase.getInstance(AppContext.context)
                    deviceDao = db.deviceDao()
                    if (null == deviceDao) {
                        deviceDao = db.deviceDao()
                    }
                    Timber.d("init scaleDao==null:${deviceDao == null}")
                    getAllDevice()
                }
            }
        }
    }

    fun saveDevice(device: WifiDevice) {
        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                deviceDao?.let { dao ->
                    dao.insert(device)
                    getAllDevice()
                }
            }
        }
    }

    fun getAllDevice() {
        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                deviceDao?.let { dao ->
                    val deviceList = dao.all
                    if (deviceList.isEmpty()) {
                        createEmptyList()
                    } else {
                        val isWifi = NetworkUtils.isWifiConnected(AppContext.context)
                        Timber.d("wifi是否连接${isWifi}")
                        deviceList.forEach { device ->
                            if (device.address.isNullOrEmpty().not()) {
                                if (!isWifi) {
                                    device.contentState = "离线"
                                }else{
                                    device.contentState = "连接"
                                }
                            }
                        }
                        _deviceListLiveData.postValue(deviceList)
                    }
                } ?: createEmptyList()
            }
        }
    }

    private fun createEmptyList() {
        val wifiDevice = WifiDevice()
        wifiDevice.type = "foot"
        val deviceList = ArrayList<WifiDevice>(1)
        deviceList.add(wifiDevice)
        _deviceListLiveData.postValue(deviceList)
    }

    private fun connectToEsp32(address: String, port: Int): Boolean {
        try {
            if (null != mClientSocket) {
                mClientSocket!!.close()
                mClientSocket = null
            }
            // 创建 Socket 并连接到 ESP32
            mClientSocket = Socket()
            mClientSocket!!.connect(InetSocketAddress(address, port), 3000)// 设置超时时间为5秒
            //val mInputStream = mClientSocket!!.getInputStream()
            //val mOutputStream = mClientSocket!!.getOutputStream()
            return true
        } catch (e: IOException) {
            e.printStackTrace()
            return false
        }
    }

    fun deleteDevice(device: WifiDevice) {
        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                deviceDao?.let { dao ->
                    dao.delete(device)
                    getAllDevice()
                }
            }
        }
    }


    fun contentToDevice(device: WifiDevice){
        ChatServer.setContentDevice(device,ChatServer.NetWork)
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                ClientSocket.contentToDevice(device)
            }
        }
    }

    override fun onCleared() {
        ClientSocket.removeConnectionListener(connectedListener)
        super.onCleared()
    }

}